import { messages, getDefaultSetOfBook, deepFullCopy, formatNumber } from "share/common";
import React from "react";
import { connect } from "react-redux";
import {
  Input,
  Modal,
  Result,
  Tabs,
  Popover,
  Menu,
  Dropdown,
  Divider,
  Button,
  Icon,
  message,
} from "antd";
import configureStore from "stores";
import errorMessage from "share/errorMessage";
import { setDefaultSetOfBook } from "actions/cache";
import SearchArea from "components/search-area";
import ListSelector from "components/list-selector";
import ResizeTable from "components/resize-table";
import SlideFrame from "components/slide-frame";
import BasicInfo from "components/basic-info";
import ExpenseTypeRenderer from "components/ExpenseTypeRenderer";
import ExportModal from "components/template/export-modal/export-modal";
import {
  getClassifyTypeSearchItem,
  getCycleSearchItem,
  getCycleLabel,
  getClassifyTypeLabel,
  getClassifyType,
} from "./config";
import service from "./service";
import ExpenseAmountRuleForm from "./ExpenseAmountRuleForm";
import ExpenseAmountRuleNewForm from "./ExpenseAmountRuleNewForm";

const { Search } = Input;
const { TabPane } = Tabs;

class ExpenseStandard extends React.Component {
  loading = false;

  constructor(props) {
    super(props);
    const setOfBooksId =
      props.expenseTypeSetOfBooks.id || props.company.setOfBooksId;
    const columns = [
      {
        title: "-",
        dataIndex: "name",
        render: (text) => (
          <Popover placement="topLeft" content={text}>
            {text || "-"}
          </Popover>
        ),
      },
      {
        title: "编码",
        dataIndex: "code",
        render: (text) => (
          <Popover placement="topLeft" content={text}>
            {text || "-"}
          </Popover>
        ),
      },
      {
        title: "额度",
        dataIndex: "amount",
        render: (text) => (
          <Popover placement="topLeft" content={formatNumber(text)}>
            {formatNumber(text)}
          </Popover>
        ),
      },
      {
        title: "生效时间段",
        dataIndex: "dateRange",
        width: 210,
        render: (text, record) => (
          <Popover
            placement="topLeft"
            content={`${record.startTime} ~ ${record.endTime}`}
          >
            {record.startTime} ~ {record.endTime}
          </Popover>
        ),
      },
      // {
      //   title: "是否管控",
      //   dataIndex: "isControl",
      //   render: (text, record) => (
      //     <Popover placement="topLeft" content={text ? "是" : "否"}>
      //       {text ? "是" : "否"}
      //     </Popover>
      //   ),
      // },
      {
        title: messages("common.operation" /* 操作 */),
        dataIndex: "operation",
        render: (text, record) => (
          <span>
            <a onClick={() => this.goEdit(record)}>{messages("common.edit")}</a>
            <Divider type="vertical" />
            <a onClick={() => this.remove(record)}>
              {messages("common.delete")}
            </a>
          </span>
        ),
      },
    ];
    this.state = {
      setOfBooksId,
      searchParams: {
        quatoId: props.routeParams.expenseAmountOID,
      },
      quatoDetailInited: false,
      quatoDetail: {
        quatoId: props.routeParams.expenseAmountOID,
      },

      loading: false,
      data: [],
      pagination: {
        pageSize: 10,
        size: 10,
        total: 0,
        current: 1, // 从1开始，传给接口调用是要减1
      },
      showSlideFrameNew: false,
      showSlideFrameEdit: false,
      slideParams: {},
      columns,
      keyword: "", // 搜索关键词
    };
  }

  componentDidMount() {
    this.init();
  }

  init = async () => {
    let res1 = null;
    let error = null;
    try {
      res1 = await service.getQuato({
        quatoId: this.state.searchParams.quatoId,
      });
      if (res1.status !== 200) {
        message.error("error");
        return;
      }
    } catch (e) {
      error = e;
    }
    if (error) {
      message.error(e.message);
      return;
    }

    const quatoDetail = res1.data;
    const columns = this.state.columns.slice();
    columns[0].title = getClassifyType(quatoDetail.classifyType).title;
    this.setState(
      {
        columns,
        quatoDetail,
        quatoDetailInited: true,
      },
      () => {
        this.search();
      }
    );
  };

  goEdit = (editRecord) => {
    this.setState({
      showSlideFrameEdit: true,
      editRecord,
    });
  };

  removeItem = async (record) => {
    try {
      await service.deleteDetail(record);
      this.search();
    } catch (e) {
      if (e.response) {
        errorMessage(e.response);
      } else {
        message.error(e.message);
      }
    }
  };

  remove = (record) => {
    Modal.confirm({
      title: "确认删除吗",
      content: "点击删除将删除此记录",
      onOk: () => {
        this.removeItem(record);
      },
      onCancel() {},
    });
  };

  search = async (result = {}, again = false) => {
    if (this.loading && !again) return;
    this.loading = true;
    const { searchParams: stateSearchParams, pagination, keyword } = this.state;
    this.setState({ loading: true });
    try {
      const searchParams = { ...stateSearchParams };
      if (result.keyword) {
        searchParams.keyword = result.keyword;
      } else {
        searchParams.keyword = keyword;
      }
      const res = await service.searchQuato({ ...searchParams, ...pagination });
      if (res.data.length === 0 && pagination.current > 1) {
        const newPagination = deepFullCopy(pagination);
        newPagination.current = pagination.current - 1;
        newPagination.onChange = this.onChangePaper;
        this.setState(
          {
            pagination: newPagination,
          },
          () => {
            this.search({}, true);
          }
        );
      } else {
        this.setState({
          data: res.data,
          loading: false,
          pagination: {
            pageSize: pagination.pageSize,
            size: pagination.size,
            total: Number(res.headers["x-total-count"]),
            current: pagination.current,
            onChange: this.onChangePaper,
          },
          keyword: searchParams.keyword,
        });
      }
    } catch (e) {
      let errMessage = e.message;
      if (e.response && e.response.data.message) {
        errMessage = e.response.data.message;
      }
      message.error(errMessage);
    } finally {
      this.loading = false;
      this.setState({ loading: false });
    }
  };

  clear = () => {
    this.setState({
      data: [],
      pagination: {
        pageSize: this.state.pagination.pageSize,
        size: this.state.pagination.size,
        total: 0,
        current: 1,
        onChange: this.onChangePaper,
      },
    });
  };

  handleCreate = () => {
    this.setState({
      showSlideFrameNew: true,
    });
  };

  handleExport = () => {};

  handleCloseSlide = (shouldRefresh) => {
    const pagination = Object.assign({}, this.state.pagination, { current: 1 });
    this.setState(
      {
        showSlideFrameNew: false,
        showSlideFrameEdit: false,
        pagination,
      },
      () => {
        if (shouldRefresh) {
          this.search();
        }
      }
    );
  };

  onChangePaper = (page, size) => {
    const { pagination } = this.state;
    const newPagination = Object.assign({}, pagination, {
      current: page,
      size,
      pageSize: size,
    });
    this.setState(
      {
        pagination: newPagination,
      },
      () => {
        this.search();
      }
    );
  };

  render() {
    const {
      quatoDetail,
      quatoDetailInited,
      searchParams,
      loading,
      data,
      columns,
      pagination,
      setOfBooksId,
      editRecord,
      slideParams,
      showSlideFrameEdit,
      showSlideFrameNew,
    } = this.state;

    return (
      <div>
        <BasicInfo
          isHideEditBtn
          infoList={[
            {
              type: "custom",
              label: "费用类型",
              id: "name",
              render: ({ data }) => data,
              // return <ExpenseTypeRenderer id={data} />
            },
            {
              type: "custom",
              label: "分类",
              id: "classifyType",
              render: ({ data }) => getClassifyTypeLabel(data),
            },
            {
              type: "custom",
              label: "周期",
              id: "cycle",
              render: ({ data }) => getCycleLabel(data),
            },
          ]}
          infoData={quatoDetail}
        />

        <div
          className="table-header"
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <div
            className="table-header-buttons"
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "flex-start",
            }}
          >
            <Button onClick={this.handleCreate} type="primary">
              批量新建
            </Button>
            <ExportModal
              type="btn"
              exportTitle="导出数据"
              exportType="QUATO_DETAIL"
              btnType="secondary"
              exportCondition={{
                keyword: searchParams.keyword,
                quatoId: searchParams.quatoId,
              }}
              exportCommand="QUATO_DETAIL"
            />
          </div>

          <Search
            placeholder="关键词"
            enterButton
            onSearch={(value) => {
              const paginationTemp = Object.assign({}, this.state.pagination, {
                current: 1,
              });
              this.setState(
                {
                  pagination: paginationTemp,
                  keyword: value,
                },
                () => {
                  this.search({ keyword: value });
                }
              );
            }}
            style={{ width: 200 }}
          />
        </div>
        <div style={{ margin: "10px 0" }}>
          {" "}
          {
            messages("setting.key1589", {
              arg1: pagination.total,
            }) /* 共搜索到{arg1}条数据 */
          }
        </div>
        {quatoDetailInited && (
          <ResizeTable
            rowKey="adCode"
            loading={loading}
            dataSource={data}
            columns={columns}
            key={this.state.columns[0].title}
            pagination={pagination}
            size="middle"
            bordered
          />
        )}
        {quatoDetailInited && (
          <SlideFrame
            title="费用额度明细详情"
            show={showSlideFrameEdit}
            content={ExpenseAmountRuleForm}
            afterClose={this.handleCloseSlide}
            onClose={() => this.setState({ showSlideFrameEdit: false })}
            params={{
              quatoId: searchParams.quatoId,
              classifyType: quatoDetail.classifyType,
              cycle: quatoDetail.cycle,
              record: editRecord,
              setOfBooksId,
            }}
          />
        )}

        {quatoDetailInited && (
          <SlideFrame
            title="批量新建费用额度明细"
            show={showSlideFrameNew}
            content={ExpenseAmountRuleNewForm}
            afterClose={this.handleCloseSlide}
            onClose={() => this.setState({ showSlideFrameNew: false })}
            params={{
              show: showSlideFrameNew,
              quatoId: searchParams.quatoId,
              classifyType: quatoDetail.classifyType,
              cycle: quatoDetail.cycle,
              setOfBooksId,
            }}
          />
        )}
      </div>
    );
  }
}

ExpenseStandard.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    expenseTypeSetOfBooks: state.setting.expenseTypeSetOfBooks,
    tenantMode: state.main.tenantMode,
  };
}

export default connect(mapStateToProps)(ExpenseStandard);
